/* eslint-disable react/prop-types */
// PortalEditor.tsx

import React, { useState, useRef } from "react";
import { Responsive, WidthProvider } from "react-grid-layout";
import "./index.less"; // 引入样式文件
import "react-grid-layout/css/styles.css";
import "react-resizable/css/styles.css";
import { useDrop, useDrag } from "ahooks";

const GridLayout = WidthProvider(Responsive);
const DragItem = ({ data, onDragging = () => {} }) => {
	const dragRef = useRef(null);

	const [dragging, setDragging] = useState(false);

	useDrag(data, dragRef, {
		onDragStart: () => {
			setDragging(true);
		},
		onDragEnd: () => {
			setDragging(false);
		}
	});

	return (
		<div className="sidebar-component" ref={dragRef}>
			{data}
		</div>
	);
};
const PortalEditor: React.FC = () => {
	const [components, setComponents] = useState([]);
	const [nextId, setNextId] = useState(1);
	const [selectedComponent, setSelectedComponent] = useState(null);
	const handleDrop = (type: string) => {
		const newComponent = {
			id: `component-${nextId}`,
			type,
			x: 0,
			y: 0,
			w: 2,
			h: 1,
			style: { background: "#cccc", border: "1px solid black" }
		};
		setComponents([...components, newComponent]);
		setNextId(nextId + 1);
	};

	const dropRef = useRef(null);

	useDrop(dropRef, {
		onDom: (content: string, e) => {
			const newComponent = {
				id: `component-${nextId}`,
				content,
				x: 0,
				y: 0,
				w: 2,
				h: 1,
				style: { background: "#cccc", border: "1px solid black" }
			};
			setComponents([...components, newComponent]);
			setNextId(nextId + 1);
			// alert(`custom: ${content} dropped`);
		},
		onDragEnter: () => setIsHovering(true),
		onDragLeave: () => setIsHovering(false)
	});
	const handleClickComponent = (id: string) => {
		// 点击组件时设置为选中状态
		setSelectedComponent(id);
	};

	const handleClickBlank = () => {
		// 点击空白处取消选中状态
		setSelectedComponent(null);
	};

	return (
		<div className="portal-editor">
			{/* 左侧区域 */}
			<div className="sidebar">
				{/* 左侧拖拽组件 */}
				{["Text", "News", "Image"].map((item, index) => {
					return <DragItem key={index} data={item} onDragging={data => handleDrop(data)} />;
				})}
			</div>

			{/* 中间区域 */}
			<div className="main-content" ref={dropRef}>
				<GridLayout
					className="layout"
					cols={{ lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }}
					rowHeight={100}
					autoResize
					width={1200}
					breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
				>
					{/* 渲染所有组件 */}
					{components.map(component => (
						<div
							key={component.id}
							style={{ ...component.style, border: component.id === selectedComponent ? "2px solid blue" : "1px solid black" }}
							onClick={() => handleClickComponent(component.id)}
						>
							{component.type} Component
						</div>
					))}
				</GridLayout>
			</div>

			{/* 右侧显示属性 */}
			<div className="properties-panel">Properties</div>
		</div>
	);
};

export default PortalEditor;
